
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { Label } from "@/components/ui/label";
import { Progress } from "@/components/ui/progress";
import { toast } from "@/components/ui/sonner";
import { Badge } from "@/components/ui/badge";
import { Brain, Award, Crown } from "lucide-react";

interface Question {
  id: number;
  text: string;
  options: {
    value: string;
    label: string;
    strength: string;
  }[];
}

const strengthQuestions: Question[] = [
  {
    id: 1,
    text: "When faced with a complex problem, I typically:",
    options: [
      { value: "analytical", label: "Break it down into logical steps and analyze each part methodically", strength: "Analytical Thinking" },
      { value: "creative", label: "Think outside the box and come up with innovative solutions", strength: "Creative Problem Solving" },
      { value: "collaborative", label: "Discuss it with others to gain different perspectives", strength: "Collaborative Problem Solving" },
      { value: "intuitive", label: "Trust my intuition and past experiences to guide my approach", strength: "Intuitive Decision Making" }
    ]
  },
  {
    id: 2,
    text: "When learning something new, I excel at:",
    options: [
      { value: "conceptual", label: "Understanding abstract concepts and theories", strength: "Conceptual Thinking" },
      { value: "practical", label: "Applying knowledge to practical, real-world situations", strength: "Practical Application" },
      { value: "reflective", label: "Reflecting on experiences and drawing meaningful insights", strength: "Reflective Learning" },
      { value: "experimental", label: "Experimenting and learning through trial and error", strength: "Experimental Learning" }
    ]
  },
  {
    id: 3,
    text: "In team settings, my greatest contribution is usually:",
    options: [
      { value: "leadership", label: "Providing direction and helping the team stay focused", strength: "Leadership" },
      { value: "support", label: "Supporting team members and maintaining positive relationships", strength: "Supportive Collaboration" },
      { value: "execution", label: "Getting things done efficiently and meeting deadlines", strength: "Execution Excellence" },
      { value: "innovation", label: "Coming up with new ideas and approaches", strength: "Innovative Thinking" }
    ]
  },
  {
    id: 4,
    text: "When facing a setback, I typically:",
    options: [
      { value: "resilience", label: "Bounce back quickly and try again with renewed determination", strength: "Resilience" },
      { value: "adaptive", label: "Adapt my approach based on what I learned from the failure", strength: "Adaptability" },
      { value: "analytical", label: "Carefully analyze what went wrong to avoid similar mistakes", strength: "Critical Analysis" },
      { value: "support-seeking", label: "Seek feedback and support from others to improve", strength: "Feedback Receptiveness" }
    ]
  },
  {
    id: 5,
    text: "I feel most energized when I am:",
    options: [
      { value: "achievement", label: "Accomplishing goals and checking items off my list", strength: "Achievement Drive" },
      { value: "learning", label: "Learning something new and expanding my knowledge", strength: "Continuous Learning" },
      { value: "helping", label: "Helping others succeed and reach their potential", strength: "Empowering Others" },
      { value: "creating", label: "Creating something original or improving existing systems", strength: "Creative Innovation" }
    ]
  }
];

export function StrengthsFinder() {
  const [currentQuestion, setCurrentQuestion] = useState(0);
  const [answers, setAnswers] = useState<Record<number, string>>({});
  const [strengths, setStrengths] = useState<string[]>([]);
  const [currentAnswer, setCurrentAnswer] = useState<string>("");
  const [isComplete, setIsComplete] = useState(false);
  
  const handleNext = () => {
    if (!currentAnswer) {
      toast.error("Please select an answer before continuing");
      return;
    }
    
    const updatedAnswers = { ...answers, [strengthQuestions[currentQuestion].id]: currentAnswer };
    setAnswers(updatedAnswers);
    
    if (currentQuestion < strengthQuestions.length - 1) {
      setCurrentQuestion(currentQuestion + 1);
      setCurrentAnswer("");
    } else {
      // Calculate strengths when all questions are answered
      analyzeStrengths(updatedAnswers);
      setIsComplete(true);
    }
  };
  
  const analyzeStrengths = (answers: Record<number, string>) => {
    // Count which strengths appear most based on answers
    const strengthMap: Record<string, number> = {};
    
    Object.entries(answers).forEach(([questionId, value]) => {
      const question = strengthQuestions.find(q => q.id === Number(questionId));
      if (question) {
        const option = question.options.find(opt => opt.value === value);
        if (option) {
          strengthMap[option.strength] = (strengthMap[option.strength] || 0) + 1;
        }
      }
    });
    
    // Get top 3 strengths
    const topStrengths = Object.entries(strengthMap)
      .sort((a, b) => b[1] - a[1])
      .slice(0, 3)
      .map(([strength]) => strength);
      
    setStrengths(topStrengths);
  };
  
  const restartQuiz = () => {
    setCurrentQuestion(0);
    setAnswers({});
    setCurrentAnswer("");
    setStrengths([]);
    setIsComplete(false);
  };
  
  const progress = ((currentQuestion + (isComplete ? 1 : 0)) / strengthQuestions.length) * 100;
  
  return (
    <Card className="w-full max-w-xl mx-auto">
      <CardHeader>
        <CardTitle className="flex items-center justify-between">
          {isComplete ? "Your Core Strengths" : "Strengths Finder Assessment"}
          <span className="text-sm font-normal text-muted-foreground">
            {!isComplete && `${currentQuestion + 1}/${strengthQuestions.length}`}
          </span>
        </CardTitle>
        {!isComplete && (
          <Progress value={progress} className="h-2 mt-2" />
        )}
      </CardHeader>
      
      <CardContent>
        {!isComplete ? (
          <>
            <h3 className="text-lg font-medium mb-4">{strengthQuestions[currentQuestion].text}</h3>
            <RadioGroup value={currentAnswer} onValueChange={setCurrentAnswer} className="space-y-3">
              {strengthQuestions[currentQuestion].options.map((option) => (
                <div key={option.value} className="flex items-center space-x-2 rounded-md border p-3 cursor-pointer hover:bg-muted">
                  <RadioGroupItem value={option.value} id={option.value} />
                  <Label htmlFor={option.value} className="flex-grow cursor-pointer">{option.label}</Label>
                </div>
              ))}
            </RadioGroup>
          </>
        ) : (
          <div className="space-y-6 py-4">
            <div className="text-center mb-6">
              <Crown className="w-12 h-12 text-primary mx-auto mb-4" />
              <h3 className="text-xl font-semibold mb-2">Your Top 3 Strengths</h3>
              <p className="text-muted-foreground">Based on your responses, we've identified your core strengths</p>
            </div>
            
            <div className="space-y-4">
              {strengths.map((strength, index) => (
                <div key={strength} className="flex items-center gap-3 p-4 rounded-lg bg-accent/30">
                  <div className="flex items-center justify-center w-8 h-8 rounded-full bg-primary text-primary-foreground">
                    {index + 1}
                  </div>
                  <div>
                    <h4 className="font-medium">{strength}</h4>
                    <p className="text-sm text-muted-foreground">
                      {index === 0 ? "Your dominant strength" : index === 1 ? "Your secondary strength" : "Your supporting strength"}
                    </p>
                  </div>
                </div>
              ))}
            </div>
            
            <div className="bg-muted p-4 rounded-lg mt-6">
              <h4 className="font-medium flex items-center gap-2 mb-2">
                <Award className="w-4 h-4 text-primary" />
                Recommended Focus Areas
              </h4>
              <p className="text-sm text-muted-foreground mb-3">
                Consider developing these strengths further through these activities:
              </p>
              <div className="flex flex-wrap gap-2">
                <Badge variant="secondary" className="bg-accent/50">Problem-Based Learning</Badge>
                <Badge variant="secondary" className="bg-accent/50">Group Projects</Badge>
                <Badge variant="secondary" className="bg-accent/50">Research Activities</Badge>
                <Badge variant="secondary" className="bg-accent/50">Leadership Opportunities</Badge>
              </div>
            </div>
          </div>
        )}
      </CardContent>
      
      <CardFooter className="flex justify-between">
        {!isComplete ? (
          <>
            <Button variant="ghost" onClick={() => currentQuestion > 0 && setCurrentQuestion(currentQuestion - 1)} disabled={currentQuestion === 0}>
              Back
            </Button>
            <Button onClick={handleNext}>
              {currentQuestion < strengthQuestions.length - 1 ? "Next" : "Complete"}
            </Button>
          </>
        ) : (
          <Button onClick={restartQuiz} className="w-full">
            Retake Assessment
          </Button>
        )}
      </CardFooter>
    </Card>
  );
}
